package us.mooresr.geartrack.server.handler;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import us.mooresr.geartrack.server.DAO;
import us.mooresr.geartrack.shared.action.GetAllCheckedOutItemsAction;
import us.mooresr.geartrack.shared.action.GetAllCheckedOutItemsResult;
import us.mooresr.geartrack.shared.model.Item;
import us.mooresr.geartrack.shared.model.Loan;
import us.mooresr.geartrack.shared.model.LoanDTO;
import us.mooresr.geartrack.shared.model.Person;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Query;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class GetAllCheckedOutItemsActionHandler 
	implements ActionHandler<GetAllCheckedOutItemsAction, GetAllCheckedOutItemsResult> {

	@Override
	public GetAllCheckedOutItemsResult execute(
			GetAllCheckedOutItemsAction arg0, ExecutionContext arg1)
			throws ActionException {
		DAO dao = new DAO();
		
		Objectify ofy = dao.ofy();
		

		
		List<Loan> loanList =  ofy.query(Loan.class).filter("checkInDate", null).list();
		HashSet<Long> itemKeys = new HashSet<Long>();
		
		for (Loan l : loanList) {
			itemKeys.add(l.getItemId());
		}
		
		Map<Long, Item> itemMap = dao.ofy().get(Item.class, itemKeys);
		
		ArrayList<Item> resultList = new ArrayList<Item>(itemMap.values());
		
		return new GetAllCheckedOutItemsResult(resultList);
		
	}

	@Override
	public Class<GetAllCheckedOutItemsAction> getActionType() {
		return GetAllCheckedOutItemsAction.class;
	}

	@Override
	public void undo(GetAllCheckedOutItemsAction arg0,
			GetAllCheckedOutItemsResult arg1, ExecutionContext arg2)
			throws ActionException {
		// TODO Auto-generated method stub
		
	}

}
